import type { PCBuild, Recommendation } from '../types/components';
import { cpus, gpus, rams, motherboards, storages, powerSupplies, pcCases, cpuCoolers } from '../data/mockData';
import { compatibilityChecker } from './compatibilityChecker';

// 推荐系统类
export class RecommendationSystem {
  // 根据预算和使用场景生成推荐配置
  public generateRecommendations(
    budget: number, 
    usageType: 'gaming' | 'workstation' | 'budget' | 'balanced' = 'balanced',
    count: number = 3
  ): Recommendation[] {
    const recommendations: Recommendation[] = [];
    const triedConfigs: Set<string> = new Set();

    // 根据使用场景调整组件权重
    const weights = this.getWeightsByUsageType(usageType);

    // 生成尽可能多的配置，直到达到指定数量或尝试次数过多
    let attempts = 0;
    const maxAttempts = 1000;

    while (recommendations.length < count && attempts < maxAttempts) {
      attempts++;
      
      // 随机生成一个配置
      const build = this.generateRandomBuild(weights);
      
      // 检查兼容性
      const compatibility = compatibilityChecker.checkCompatibility(build);
      if (!compatibility.isCompatible) {
        continue;
      }
      
      // 计算总价
      const totalPrice = this.calculateTotalPrice(build);
      
      // 检查预算
      if (totalPrice > budget * 1.1 || totalPrice < budget * 0.8) {
        continue;
      }
      
      // 计算综合性能评分
      const performanceScore = this.calculatePerformanceScore(build, weights);
      
      // 生成配置ID，用于去重
      const configId = this.generateConfigId(build);
      if (triedConfigs.has(configId)) {
        continue;
      }
      triedConfigs.add(configId);
      
      // 添加到推荐列表
      recommendations.push({
        name: this.generateConfigName(build, usageType),
        description: this.generateConfigDescription(build, usageType),
        totalPrice,
        performanceScore,
        build
      });
    }
    
    // 按性价比排序（性能/价格）
    recommendations.sort((a, b) => (b.performanceScore / b.totalPrice) - (a.performanceScore / a.totalPrice));
    
    return recommendations.slice(0, count);
  }

  // 根据使用场景获取组件权重
  private getWeightsByUsageType(usageType: string): Record<string, number> {
    const baseWeights = {
      cpu: 0.25,
      gpu: 0.3,
      ram: 0.15,
      motherboard: 0.1,
      storage: 0.1,
      powerSupply: 0.05,
      pcCase: 0.03,
      cpuCooler: 0.02
    };

    switch (usageType) {
      case 'gaming':
        return {
          ...baseWeights,
          gpu: 0.4,  // 游戏场景GPU更重要
          cpu: 0.2
        };
      case 'workstation':
        return {
          ...baseWeights,
          cpu: 0.35,  // 工作站场景CPU更重要
          ram: 0.2,
          storage: 0.15
        };
      case 'budget':
        // 预算场景下，各个组件权重相对均衡，但更注重价格
        return baseWeights;
      case 'balanced':
      default:
        return baseWeights;
    }
  }

  // 随机生成一个配置
  private generateRandomBuild(weights: Record<string, number>): PCBuild {
    const build: PCBuild = {};

    // 随机选择CPU
    build.cpu = this.selectRandomComponent(cpus, weights.cpu || 0.25);
    
    // 如果选择了CPU，选择兼容的主板
    if (build.cpu) {
      const compatibleMotherboards = motherboards.filter(mb => mb.socketType === build.cpu!.socketType);
      if (compatibleMotherboards.length > 0) {
        build.motherboard = this.selectRandomComponent(compatibleMotherboards, weights.motherboard || 0.1);
      }
    }

    // 如果选择了主板，选择兼容的内存
    if (build.motherboard) {
      const compatibleRAMs = rams.filter(ram => ram.type === build.motherboard!.memoryType);
      if (compatibleRAMs.length > 0) {
        build.ram = this.selectRandomComponent(compatibleRAMs, weights.ram || 0.15);
      }
    }

    // 随机选择其他组件
    build.gpu = this.selectRandomComponent(gpus, weights.gpu || 0.3);
    build.storage = this.selectRandomComponent(storages, weights.storage || 0.1);
    build.powerSupply = this.selectRandomComponent(powerSupplies, weights.powerSupply || 0.05);
    build.pcCase = this.selectRandomComponent(pcCases, weights.pcCase || 0.03);
    build.cpuCooler = this.selectRandomComponent(cpuCoolers, weights.cpuCooler || 0.02);

    return build;
  }

  // 随机选择一个组件，权重影响选择概率
  private selectRandomComponent<T extends { id: string; price: number; performanceScore: number }>(
    components: T[], 
    weight: number
  ): T | undefined {
    if (components.length === 0) return undefined;

    // 简化的随机选择
    // 在实际应用中，可以根据权重、价格和性能进行更复杂的选择
    const randomIndex = Math.floor(Math.random() * components.length);
    return components[randomIndex];
  }

  // 计算配置总价
  private calculateTotalPrice(build: PCBuild): number {
    let total = 0;
    
    if (build.cpu) total += build.cpu.price;
    if (build.gpu) total += build.gpu.price;
    if (build.ram) total += build.ram.price;
    if (build.motherboard) total += build.motherboard.price;
    if (build.storage) total += build.storage.price;
    if (build.powerSupply) total += build.powerSupply.price;
    if (build.pcCase) total += build.pcCase.price;
    if (build.cpuCooler) total += build.cpuCooler.price;
    
    return total;
  }

  // 计算综合性能评分
  private calculatePerformanceScore(build: PCBuild, weights: Record<string, number>): number {
    let score = 0;
    let totalWeight = 0;
    
    if (build.cpu) {
      score += build.cpu.performanceScore * (weights.cpu || 0);
      totalWeight += (weights.cpu || 0);
    }
    if (build.gpu) {
      score += build.gpu.performanceScore * (weights.gpu || 0);
      totalWeight += (weights.gpu || 0);
    }
    if (build.ram) {
      score += build.ram.performanceScore * (weights.ram || 0);
      totalWeight += (weights.ram || 0);
    }
    if (build.motherboard) {
      score += build.motherboard.performanceScore * (weights.motherboard || 0);
      totalWeight += (weights.motherboard || 0);
    }
    if (build.storage) {
      score += build.storage.performanceScore * (weights.storage || 0);
      totalWeight += (weights.storage || 0);
    }
    if (build.powerSupply) {
      score += build.powerSupply.performanceScore * (weights.powerSupply || 0);
      totalWeight += (weights.powerSupply || 0);
    }
    if (build.pcCase) {
      score += build.pcCase.performanceScore * (weights.pcCase || 0);
      totalWeight += (weights.pcCase || 0);
    }
    if (build.cpuCooler) {
      score += build.cpuCooler.performanceScore * (weights.cpuCooler || 0);
      totalWeight += (weights.cpuCooler || 0);
    }
    
    // 归一化分数
    return totalWeight > 0 ? Math.round(score / totalWeight) : 0;
  }

  // 生成配置ID，用于去重
  private generateConfigId(build: PCBuild): string {
    const ids: string[] = [];
    
    if (build.cpu) ids.push(build.cpu.id);
    if (build.gpu) ids.push(build.gpu.id);
    if (build.ram) ids.push(build.ram.id);
    if (build.motherboard) ids.push(build.motherboard.id);
    if (build.storage) ids.push(build.storage.id);
    
    return ids.sort().join('-');
  }

  // 生成配置名称
  private generateConfigName(build: PCBuild, usageType: string): string {
    const usageNames: Record<string, string> = {
      gaming: '游戏主机',
      workstation: '工作站',
      budget: '经济型主机',
      balanced: '均衡配置'
    };

    const parts: string[] = [];
    parts.push(usageNames[usageType] || '电脑配置');
    
    if (build.cpu) {
      parts.push(build.cpu.name.split(' ')[2] || ''); // 获取CPU系列
    }
    
    if (build.gpu) {
      parts.push(build.gpu.name.split(' ')[2] || ''); // 获取GPU系列
    }
    
    return parts.join(' - ');
  }

  // 生成配置描述
  private generateConfigDescription(build: PCBuild, usageType: string): string {
    const descriptions: string[] = [];
    
    switch (usageType) {
      case 'gaming':
        descriptions.push('高性能游戏配置，畅玩各种3A大作');
        break;
      case 'workstation':
        descriptions.push('专业工作站配置，适合设计和开发工作');
        break;
      case 'budget':
        descriptions.push('高性价比配置，经济实惠又实用');
        break;
      case 'balanced':
        descriptions.push('均衡配置，兼顾性能和价格');
        break;
    }
    
    if (build.cpu && build.gpu) {
      descriptions.push(`搭载${build.cpu.brand} ${build.cpu.name.split(' ')[2] || ''}处理器和${build.gpu.brand} ${build.gpu.name.split(' ')[2] || ''}显卡`);
    }
    
    if (build.ram) {
      descriptions.push(`${build.ram.capacity}GB ${build.ram.type}内存`);
    }
    
    return descriptions.join('，');
  }
}

// 导出推荐系统实例
export const recommendationSystem = new RecommendationSystem();